//
//  NewComplainController.m
//  protesteya
//
//  Created by Sebastian Bene on 9/23/13.
//  Copyright (c) 2013 Obligatorio Dispositivos Moviles. All rights reserved.
//

#import "NewComplainController.h"
#import "TwitterInvoker.h"
#import "ResponseParser.h"
#import "DejalActivityView.h"
#import <QuartzCore/QuartzCore.h>

@interface NewComplainController () <UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (strong, nonatomic) IBOutlet UITextField *textComplain;
@property (strong, nonatomic) IBOutlet UIImageView *imageComplain;
@property (weak, nonatomic) IBOutlet UIButton *sendButton;

@end

@implementation NewComplainController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSString* fontName = @"Avenir-Book";    
    
    self.elementContainer.layer.cornerRadius = 3.0f;
    
    self.imageComplain.backgroundColor = [UIColor whiteColor];
    self.imageComplain.layer.cornerRadius = 3.0f;
    
    self.textComplain.layer.cornerRadius = 3.0f;
    self.textComplain.leftViewMode = UITextFieldViewModeAlways;
    UIView* leftView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    self.textComplain.leftView = leftView1;
    self.textComplain.font = [UIFont fontWithName:fontName size:16.0f];

    _invoker = [[TwitterInvoker alloc] init];
    self.textComplain.delegate = self;
}

- (IBAction)sendNewComplain:(UIButton *)sender {
    [self.textComplain resignFirstResponder];
    [DejalBezelActivityView activityViewForView:self.view withLabel:@"Enviando Protesta..."];
        
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];   
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    _locationManager = nil;
}

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    SendTweetRequest *request = [[SendTweetRequest alloc] init];
    request.text = self.textComplain.text;
    request.latitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.latitude];
    request.longitude = [NSString stringWithFormat:@"%f", _locationManager.location.coordinate.longitude];
    request.image = _imageComplain.image;
    
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    _locationManager = nil;
    
    _invoker.tweeterInvokerDelegate = self;
    [_invoker SendTweet:request];
}

-(void)getResponse:(NSDictionary *)response
{
    ResponseParser *parser = [[ResponseParser alloc] init];
    TwitterBaseResponse *sendTweetResponse = [parser ParseTwitterBaseResponse:response];
    
    if(sendTweetResponse.responseType == TwitterResponseError)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [DejalBezelActivityView removeViewAnimated:YES];
        });
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:sendTweetResponse.errorMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
    }
    else
    {
        _invoker.tweeterInvokerDelegate = nil;
        dispatch_async(dispatch_get_main_queue(), ^{
            [DejalBezelActivityView removeViewAnimated:YES];
            [self.navigationController popViewControllerAnimated:YES];
        });
    }    
}

- (IBAction)selectImage:(UIButton *)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"Seleccione Imagen", nil)
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancelar", nil)
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:NSLocalizedString(@"Tomar nueva Imagen", nil),
                                  NSLocalizedString(@"Seleccionar Existente", nil), nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	actionSheet.destructiveButtonIndex = 2;
	[actionSheet showFromToolbar:self.navigationController.toolbar];
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0)
	{
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self presentViewController:picker animated:YES completion:NULL];
        }
        else
        {
            UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                  message:@"El dispositivo no posee camara"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"OK"
                                                        otherButtonTitles: nil];
            
            [myAlertView show];
        }
	}
	else if(buttonIndex == 1)
	{
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:picker animated:YES completion:NULL];
	}
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    _imageComplain.image = chosenImage;
    _imageComplain.hidden = NO;
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > 100) ? NO : YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self sendNewComplain:nil];
    return YES;
}

#define kOFFSET_FOR_KEYBOARD 170.0

-(void)keyboardWillShow {
    // Animate the current view out of the way
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)keyboardWillHide {
    if (self.view.frame.origin.y >= 0)
    {
        [self setViewMovedUp:YES];
    }
    else if (self.view.frame.origin.y < 0)
    {
        [self setViewMovedUp:NO];
    }
}

-(void)textFieldDidBeginEditing:(UITextField *)sender
{
    if ([sender isEqual:self.textComplain])
    {
        //move the main view, so that the keyboard does not hide it.
        if  (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
    }
}

//method to move the view up/down whenever the keyboard is shown/dismissed
-(void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3]; // if you want to slide up the view
    
    CGRect rect = self.view.frame;
    if (movedUp)
    {
        // 1. move the view's origin up so that the text field that will be hidden come above the keyboard
        // 2. increase the size of the view so that the area behind the keyboard is covered up.
        rect.origin.y -= kOFFSET_FOR_KEYBOARD;
        rect.size.height += kOFFSET_FOR_KEYBOARD;
    }
    else
    {
        // revert back to the normal state.
        rect.origin.y += kOFFSET_FOR_KEYBOARD;
        rect.size.height -= kOFFSET_FOR_KEYBOARD;
    }
    self.view.frame = rect;
    
    [UIView commitAnimations];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [[event allTouches] anyObject];
    if ([_textComplain isFirstResponder] && [touch view] != _textComplain) {
        [_textComplain resignFirstResponder];
        if (self.view.frame.origin.y >= 0)
        {
            [self setViewMovedUp:YES];
        }
        else if (self.view.frame.origin.y < 0)
        {
            [self setViewMovedUp:NO];
        }
    }
    [super touchesBegan:touches withEvent:event];
}
@end
